/*
 * fractal.c
 *
 *  Created on: 29/10/2008
 *      Author: row
 */

#include <stdio.h>
#include <unistd.h>
#include <fcntl.h>
#include <img.h>
#include <xlib.h>
#include <math.h>

#define RACCOON_FILE "/usr/raccoon.bmp"
#define INC 1
#define PI (3.141592653589793)

int init(imgT ** screen);
void animate(imgT * screen);

int main(int argc, char ** argv)
{
	imgT * screen;


	if (init(&screen) == 0)
		return 0;

	animate(screen);

	imgFree(screen);

	return 0;
}

int init(imgT ** screen)
{

	if ((*screen = imgScreen(2)) == NULL)
	{
		printf("Couldn't create screen, not enough memory.\n");
		return 0;
	}

	return 1;
}


void fractal(imgT * screen, int length, int minLen, pointT p0, double w, colorT color) {
	
	if (length < minLen) {
		pointT p1;
		p1.x = p0.x + cos(w)*length;
		p1.y = p0.y + sin(w)*length;
		drawLine(screen, p0, p1, color);
		return;
	}
	
	length /= 3;
	
	fractal(screen, length, minLen, p0, w, color);
	p0.x += cos(w)*length;
	p0.y += sin(w)*length;
	w += PI/3;
	fractal(screen, length, minLen, p0, w, color);
	p0.x += cos(w)*length;
	p0.y += sin(w)*length;
	w -= 2*PI/3;
	fractal(screen, length, minLen, p0, w, color);
	p0.x += cos(w)*length;
	p0.y += sin(w)*length;
	w += PI/3;
	fractal(screen, length, minLen, p0, w, color);
}


void animate(imgT * screen)
{
	rectT pos, mask, racc, buff, frst;
	int offset = 0;
	int i;
	int flags,aux;
	pointT p1;
	int size;
	colorT black;
	colorT color = {0xFF, 0xFF, 0xFF};
	black.r = 0;
	black.g = 0;
	black.b = 0;

	
	imgScreenRefresh(screen);
	

	flags = fcntl(0, F_GETFL, 0);

	/*Pongo non block*/
	fcntl(0, F_SETFL, flags | O_NONBLOCK);

	p1.x = 100;
	p1.y = 300;

	while (read(0,&aux,1)==-1)
	{
        int cc;
        fractal(screen, 600, 3, p1, 0, black);
        fractal(screen, 600, 601, p1, 0, color);
        for(cc=600;cc>2; cc-=3) {
        	fractal(screen, 600, cc+3, p1, 0, black);
            fractal(screen, 600, cc, p1, 0, color);
            imgScreenRefresh(screen);
        }
		
	}

	/*Pongo block*/
	fcntl(0, F_SETFL, flags);

}
